package cn.sumpu.app.guoguojie.web.mvc.family;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.sumpu.app.guoguojie.biz.AlbumBiz;
import cn.sumpu.app.guoguojie.biz.CommentBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.domain.Album;
import cn.sumpu.app.guoguojie.domain.Comment;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.Picture;
import cn.sumpu.app.guoguojie.domain.Ext.CommentExt;
import cn.sumpu.app.guoguojie.domain.Ext.PageModel;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.Encode;
import cn.sumpu.app.guoguojie.util.IdGenerator;
import cn.sumpu.app.guoguojie.web.util.Constants;
import cn.sumpu.app.guoguojie.web.util.MultipartFileStatus;

@Controller
public class AlbumController {

	@Autowired
	private AlbumBiz albumBiz;

	@Autowired
	private ImageBiz imageBiz;
	@Autowired
	private CommentBiz commentBiz;


	


	@RequestMapping(value = "/saveAlbum.htm", method = RequestMethod.POST)
	public String saveAlbum(HttpServletRequest request,
			HttpServletResponse response) { 
		Album album = new Album();
		album.setName(request.getParameter("name"));
		album.setIdentifier(IdGenerator.createIdentifier());
		album.setDescription(request.getParameter("description"));
		album.setMember(request.getParameter("member"));
		album.setUsername(request.getParameter("username"));
		album.setVisibility(request.getParameter("visibility"));
		try {
			albumBiz.createAlbum(album);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter output = response.getWriter();
			output.print("success");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter output = response.getWriter();
				output.print("error");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	@RequestMapping(value = "/myAlbumInfo.htm", method = RequestMethod.GET)
	public String myAlbumInfo(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			List<Album> albumList = albumBiz.viewAlbum();
			request.setAttribute("albumList", albumList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/myAlbumInfo";
	}
	
	

	/**
	 * 相册初始页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumInfo.htm")
	public String viewAlbum(HttpServletRequest request,
			HttpServletResponse response) { 
		Member member = (Member) request.getSession().getAttribute("member");
		String page = request.getParameter("page");
		if(Common.empty(page)){
			page = "1";
		}
		try {
			PageModel albumPageModel = albumBiz.albumList(member.getFamily(),Integer.parseInt(page));
			request.setAttribute("albumPageModel", albumPageModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/albumInfo";
	}
	
	
	/**
	 * 我的照片分类页
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/myPhoto.htm")
	public String myPhoto(HttpServletRequest request,
			HttpServletResponse response) {
		return "album/myPhoto";
	}
	
	/**
	 * 我的照片列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/photoPage.htm")
	public String photoPage(String friendPhoto,HttpServletRequest request,HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		String page = request.getParameter("page");
		String album = request.getParameter("album");
		String photoModel = "notAll";
		
		try {
			if(Common.empty(album)){
				album = null;
				photoModel = "all";
			}else{
				Album myAlbum = albumBiz.getAlbumById(album);
				request.setAttribute("album", myAlbum);
			}
			if(Common.empty(page)){
				page = "1";
			}
			PageModel photoPageModel = albumBiz.photoList(Common.empty(friendPhoto)?member.getFamily():null,album,Integer.parseInt(page));
			request.setAttribute("photoPageModel", photoPageModel);
			request.setAttribute("friendPhoto", friendPhoto);
			request.setAttribute("photoModel", photoModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "album/photoPage";
	}
	
	
	/**
	 * 上传照片页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/uploadPhoto.htm")
	public String uploadPhoto(String albumId,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		try {
			List<Album> albumList = albumBiz.getAlbumList(member.getFamily());
			if(albumList==null || albumList.size() < 1){
				Album album = new Album();
				album.setName("默认相册");
				album.setMember(member.getIdentifier());
				album.setUsername(member.getUsername());
				Album a = albumBiz.createAlbum(album);
				albumList = new ArrayList<Album>();
				albumList.add(a);
			}
			request.setAttribute("albumId", albumId);
			request.setAttribute("albumList", albumList);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "album/uploadPhotoSwf";
	}
	
	/**
	 * 照片保存
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/uploadPhotoSave.htm")
	public String uploadPhotoSave(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			albumBiz.uploadPhoto(request);
			pw = response.getWriter();
			pw.print("success");
		} catch (Exception e) {
			e.printStackTrace();
			pw.print("error");
		}
		return null;
	}
	
	/**
	 *专辑页面列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumPage.htm")
	public String albumPage(HttpServletRequest request,HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		String page = request.getParameter("page");
		if(Common.empty(page)){
			page = "1";
		}
		try {
			PageModel albumPageModel = albumBiz.albumList(member.getFamily(),Integer.parseInt(page));
			request.setAttribute("albumPageModel", albumPageModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/albumPage";
	}
	
	/**
	 * 照片浏览
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/photoView.htm")
	public String photoView(String friendPhoto,HttpServletRequest request) {
		Member member = (Member) request.getSession().getAttribute("member");
		String album = request.getParameter("album");
		String picId = request.getParameter("picId");
		Picture photo = null;
		String index = request.getParameter("index");
		
		
		int indexTmp = 1;
		if(Common.empty(album))
			album = null;
		try {
			
			List<Picture> photoList = albumBiz.getPhotoList(Common.empty(friendPhoto)?member.getFamily():null, album);
			if(photoList!=null && photoList.size() > 0){
				if(!Common.empty(picId)){
					for (int i = 0; i < photoList.size(); i++) {
						Picture p = photoList.get(i);
						if(p.getIdentifier().equals(picId)){
							indexTmp = i + 1;
							photo = p;
							request.setAttribute("index", indexTmp);
						}
					}
				}else if(!Common.empty(index)){
					for (int i = 0; i < photoList.size(); i++) {
						Picture p = photoList.get(i);
						if(i == Integer.parseInt(index) - 1){
							photo = p;
							request.setAttribute("index", index);
						}
					}
				}
				
				if(photo==null) photo = photoList.get(0);
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("commentId", photo.getIdentifier());
			map.put("commentIdType", "pictureid");
			List<CommentExt> commentList = commentBiz.getCommentList(map);
			request.setAttribute("commentList", commentList);
			request.setAttribute("photoList", photoList);
			request.setAttribute("album", album);
			request.setAttribute("photo", photo);
			request.setAttribute("friendPhoto", friendPhoto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/photoView";
	}
	
	
	
	/**
	 * 评论页面
	 * @param picId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/photoViewComments.htm")
	public String photoViewComments(String picId,HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("commentId", picId);
		map.put("commentIdType", "pictureid");
		try {
			List<CommentExt> commentList = commentBiz.getCommentList(map);
			request.setAttribute("commentList", commentList);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "album/comments";
	}
	/**
	 * 增加照片专辑页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumAdd.htm")
	public String albumAdd(HttpServletRequest request,
			HttpServletResponse response) {
		return "album/albumAdd";
	}
	
	/**
	 * 增加照片专辑保存
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumAddSave.htm")
	public String albumAddSave(Album album,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		album.setMember(member.getIdentifier());
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			Album a = albumBiz.createAlbum(album);
			pw = response.getWriter();
			pw.print(JSONObject.fromObject(a));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改专辑页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumEdit.htm")
	public String albumEdit(String album,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		try { 
			Album obj = albumBiz.getAlbumById(album);
			List<Picture> photoList = albumBiz.getPhotoList(member.getFamily(), album);
			List<Album> albumList = albumBiz.getAlbumList(member.getFamily());
			request.setAttribute("albumList", albumList);
			request.setAttribute("album", obj);
			request.setAttribute("photoList", photoList);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		
		return "album/albumEdit";
	}
	
	/**
	 * 修改专辑保存
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumEditSave.htm")
	public String albumEditSave(HttpServletRequest request,
			HttpServletResponse response) {
//		Member member = (Member) request.getSession().getAttribute("member");
		try { 
			String escaped_json = request.getParameter("jsonData");
			String json=Encode.unescape(escaped_json);
			JSONObject jsonObject = JSONObject.fromObject(json);
			Map<String, Class<?>> m = new HashMap<String, Class<?>>();
			m.put("pictureList", Picture.class);
			Album album =  (Album) JSONObject.toBean(jsonObject, Album.class,m);
			albumBiz.saveAlbum(album);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		
		return photoPage("",request, response);
	}
	

	/**
	 * 删除专辑
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumDelete.htm")
	public String albumDelete(String album,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		String webPath = request.getSession().getServletContext().getRealPath("/");
		try {
			albumBiz.deleteAlbum(member,webPath,album);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return viewAlbum(request, response);
	}
	

	/**
	 * 删除照片
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/photoDelete.htm")
	public String photoDelete(String album,String photoId,Boolean deleteCoverFlag,String imageServer,HttpServletRequest request,
			HttpServletResponse response) {
		String webPath = request.getSession().getServletContext().getRealPath("/");
		try {
			albumBiz.deletePhoto(webPath, photoId,album,deleteCoverFlag,imageServer);
		} catch (AppBusinessException e) { 
			e.printStackTrace();
		}
		return albumEdit(album, request, response);
	}
	
	/**
	 * 评论照片
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/photoComments.htm")
	public String photoComments(String picId,String comments,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		Comment comment = new Comment();
		comment.setIdentifier(IdGenerator.createIdentifier());
		comment.setCommentId(picId);
		comment.setCommentIdType("pictureid");
		comment.setContent(comments);
		comment.setMember(member.getIdentifier());
		comment.setPostIp(request.getRemoteAddr());
		comment.setUsername(member.getUsername());
		try {
			commentBiz.insert(comment);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return photoViewComments(picId, request);
	}
	
	/**
	 * 好友照片
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/albumFriend.htm")
	public String albumFriend(String picId,String comments,HttpServletRequest request,
			HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		String page = request.getParameter("page");
		if(Common.empty(page)){
			page = "1";
		}
		try {
			PageModel albumPageModel = albumBiz.albumFriendList(member.getFamily(),Integer.parseInt(page));
			request.setAttribute("albumPageModel", albumPageModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
			
		return "album/albumFriend";
	}
	
	

	@RequestMapping(value = "/uploadPicture.htm", method = RequestMethod.GET)
	public String uploadPicture(HttpServletRequest request) {
		try {
			List<Album> albumList = albumBiz.viewAlbum();
			request.setAttribute("albumList", albumList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/uploadPicture";
	}

	@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
	public String upload(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			imageBiz.upload(request);
			pw = response.getWriter();
			pw.println("Upload success!");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				pw = response.getWriter();
				pw.println("Upload failure!");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/checkUploadSize.htm", method = RequestMethod.POST)
	public String checkUploadSize(HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			boolean sizeLimit = imageBiz.checkUploadSize(request);
			pw = response.getWriter();
			pw.println(sizeLimit);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				pw = response.getWriter();
				pw.println(false);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	@RequestMapping(value = "/uploadProgress.ajax", method = RequestMethod.POST)
	public String uploadProgress(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			HttpSession s = request.getSession(false);
			MultipartFileStatus mfs = null;
			if (null != s) {
				mfs = (MultipartFileStatus) s
						.getAttribute(Constants.MULTIPART_FILE_STATUS);
			}
			if (null != mfs) {
				pw = response.getWriter();
				pw.println(JSONObject.fromObject(mfs).toString());
				if (mfs.getBytesRead() > 0 && mfs.getContentLength() > 0
						&& mfs.getBytesRead() == mfs.getContentLength()) {
					mfs.reset();
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//浏览他家照片
	@RequestMapping(value = "/taPhotoView.htm")
	public String taPhotoView(String friendPhoto, String family,HttpServletRequest request) {
		String album = request.getParameter("album");
		String picId = request.getParameter("picId");
		Picture photo = null;
		String index = request.getParameter("index");
		
		
		int indexTmp = 1;
		if(Common.empty(album))
			album = null;
		try {
			
			List<Picture> photoList = albumBiz.getPhotoList(Common.empty(friendPhoto)?family:null, album);
			if(photoList!=null && photoList.size() > 0){
				if(!Common.empty(picId)){
					for (int i = 0; i < photoList.size(); i++) {
						Picture p = photoList.get(i);
						if(p.getIdentifier().equals(picId)){
							indexTmp = i + 1;
							photo = p;
							request.setAttribute("index", indexTmp);
						}
					}
				}else if(!Common.empty(index)){
					for (int i = 0; i < photoList.size(); i++) {
						Picture p = photoList.get(i);
						if(i == Integer.parseInt(index) - 1){
							photo = p;
							request.setAttribute("index", index);
						}
					}
				}
				
				if(photo==null) photo = photoList.get(0);
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("commentId", photo.getIdentifier());
			map.put("commentIdType", "pictureid");
			List<CommentExt> commentList = commentBiz.getCommentList(map);
			request.setAttribute("commentList", commentList);
			request.setAttribute("photoList", photoList);
			request.setAttribute("album", album);
			request.setAttribute("photo", photo);
			request.setAttribute("friendPhoto", friendPhoto);
			request.setAttribute("family", family);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/taPhotoView";
	}
	
	//他家的照片列表
	@RequestMapping(value = "/taPhotoPage.htm")
	public String taPhotoPage(String friendPhoto,HttpServletRequest request,HttpServletResponse response, String family) {
		String page = request.getParameter("page");
		String album = request.getParameter("album");
		String photoModel = "notAll";
		
		try {
			if(Common.empty(album)){
				album = null;
				photoModel = "all";
			}else{
				Album myAlbum = albumBiz.getAlbumById(album);
				request.setAttribute("album", myAlbum);
			}
			if(Common.empty(page)){
				page = "1";
			}
			PageModel photoPageModel = albumBiz.photoList(Common.empty(friendPhoto)?family:null,album,Integer.parseInt(page));
			request.setAttribute("photoPageModel", photoPageModel);
			request.setAttribute("friendPhoto", friendPhoto);
			request.setAttribute("photoModel", photoModel);
			request.setAttribute("family", family);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "album/taPhotoPage";
	}
	
	//初始化他家相册页面
	@RequestMapping(value = "/taAlbumInfo.htm")
	public String viewTaAlbum(HttpServletRequest request,
			HttpServletResponse response, String family) {
		
		String page = request.getParameter("page");
		if(Common.empty(page)){
			page = "1";
		}
		try {
			PageModel albumPageModel = albumBiz.albumList(family,Integer.parseInt(page));
			request.setAttribute("albumPageModel", albumPageModel);
			request.setAttribute("family", family);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "album/taAlbumInfo";
	}

}
